<?php

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\crm\model\Customer;
use app\crm\model\GzhSendLog;
use app\crm\model\SendMsgModel;
use app\crm\model\ShortMessageTplModel;
use app\mini\model\SendUrlModel;
use think\facade\Db;

class CustomerPushController extends ApiCommon
{
    public function test()
    {
        $customer = Customer::find(504053)->find();
        $sendMsg = new SendMsgModel();
        $res=$sendMsg->shortMessageMassHair('17637872671',[
            'content'=>"【欣奕除疤】#content#。"
        ]);
        $res = json_decode($res,true);
        $data = [];
        foreach ($res as $value)
        {
            $res = [
                'content'=>$value['tpl_content'],
                'tpl_id'=>$value['tpl_id'],
                'reason'=>$value['reason'],
            ];
            if($value['check_status']=="CHECKING")
            {
                $res['status']=0;
            }
            if($value['check_status']=="SUCCESS")
            {
                $res['status']=1;
            }
            if($value['check_status']=="FAIL")
            {
                $res['status']=2;
            }
            array_push($data,$res);
        }
//        $model = new ShortMessageTqlModel();
//        $model->insertAll($data);
    }
    public function addModel()
    {
        $sendUrlModel = new SendUrlModel();
        $request = request()->param();
        $content = $request['content']??"";
        $tplType = $request['tpl_type']??0;
        $url = "https://sms.yunpian.com/v2/tpl/add.json";
        $params = [
            'apikey' => '9616eb7d8bd7ff79ca24af3fad8f192b',
            'tpl_content'=>"【欣奕除疤】".$content,
            'notify_type'=>3,
            'tpl_type'=>$tplType,
            'callback'=>"http://burn.178590.com/mini/IndexCustomer/receiveShortMessageCheckStatus"
        ];
        $res = $sendUrlModel->send_mass_url($url,$params);
        $res = json_decode($res,true);
        if(!empty($res['code']))
        {
            return $this->failed($res['code'],$res['detail']);
        }
        $insertData = [
            'content'=>$res['tpl_content'],
            'tpl_id'=>$res['tpl_id'],
        ];
        if($res['check_status']=="CHECKING")
        {
            $insertData['status']=0;
        }
        if($res['check_status']=="SUCCESS")
        {
            $insertData['status']=1;
        }
        if($res['check_status']=="FAIL")
        {
            $insertData['status']=2;
        }
        $model = new ShortMessageTplModel();
        $res = $model->insert($insertData);
        if($res){
            return $this->success([],'添加完成');
        }else{
            return $this->failed(100,"添加模板失败");
        }

    }
    public function getTplList()
    {
        $request = request()->param();
        $status = $request['status'];
        $where = [];
        array_push($where,['deleted_at','=',0]);
        if(!empty($status))
        {
            array_push($where,['status','=',$status]);
        }
        $result = ShortMessageTplModel::where($where)->select()->toArray();
        return $this->success($result,'模板列表',count($result));
    }
    public function tplCancel()
    {
        $request = request()->param();
        $id = $request['id']??0;
        $tpl=ShortMessageTplModel::find($id);
        $tpl->deleted_at = time();
        $res = $tpl->save();
        if($res){
            return $this->success([],'删除完成');
        }else{
            return $this->failed(100,"删除模板失败");
        }
    }
    public function shortMessageMass()
    {
        $request = request()->param();
        $where = [];
        $whereOr = [];
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        if(!empty($request['telephone']))
        {
            array_push($where,['a.telephone','=',$request['telephone']]);
        }
        if(!empty($request['age']))
        {
            array_push($where,['a.age','=',$request['age']]);
        }
        if(!empty($request['sex']))
        {
            array_push($where,['a.sex','=',$request['sex']]);
        }
        if(!empty($request['scar_id']))
        {
            array_push($where,['b.customer_setting_id_type','=',$request['scar_id']]);
        }
        if(!empty($request['shop_id']))
        {
            array_push($where,['a.shop_id','=',$request['shop_id']]);
        }
        if(!empty($request['shop_type']))
        {
            array_push($where,['c.type','=',$request['shop_type']]);
        }
        if(!empty($request['is_new']))
        {
            if($request['is_new']==1)
            {
                array_push($where,['a.cj_time','=',0]);
            }else{
                array_push($where,['a.cj_time','<>',0]);
            }
        }
        if(!empty($request['effective_entry']))
        {
            if($request['effective_entry']==1)
            {
                array_push($where,['a.first_time','=',0]);
            }else{
                array_push($where,['a.first_time','<>',0]);
            }
        }
        if(!empty($request['member_classification']))
        {
            array_push($where,['a.member_classification','=',$request['member_classification']]);
        }
        if(!empty($request['membership_leve']))
        {
            array_push($where,['a.membership_leve','=',$request['membership_leve']]);
        }
        if(!empty($request['point_min']))
        {
            array_push($where,['d.total','>=',$request['point_min']]);
        }
        if(!empty($request['point_max']))
        {
            array_push($where,['d.total','<=',$request['point_max']]);
        }
        if(!empty($request['consumption_min']))
        {
            array_push($where,['a.consumption','>=',$request['consumption_min']]);
        }
        if(!empty($request['consumption_max']))
        {
            array_push($where,['a.consumption','<=',$request['consumption_max']]);
        }
        if(!empty($request['customer_type']))
        {
            $time = strtotime('-3 month');
            if($request['customer_type']==1)
            {
                array_push($whereOr,['a.final_consumption','>',$time]);
                array_push($whereOr,['a.final_service','>',$time]);
            }else{
                array_push($where,['a.final_consumption','<=',$time]);
                array_push($where,['a.final_service','<=',$time]);
            }
        }
        $result = Db::name('customer')->alias('a')
            ->field('a.id,c.shop_name,a.customer_name,a.telephone,a.sex,a.age')
            ->join('customer_scar b','b.customer_id = a.id','left')
            ->join('shop c','c.shop_id = a.shop_id','left')
            ->join('customer_point d','d.customer_id = a.id','left')
            ->distinct(true)
            ->where($where)
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            });
        $total = $result->count();
        $result = $result->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
            ->select()->toArray();
        foreach ($result as $key => $value)
        {
            $result[$key]['sex']=$value['sex']==1?'男':'女';
        }
        return $this->success($result,"数据",$total);

    }
    public function send()
    {
        $request = request()->param();
        if($request['type']=="shortMessage")
        {
            $model = new ShortMessageTplModel();
            $res = $model->shortMessageMass($request['tel'],$request['tpl_id'],$this->userInfo['id']);
        }else{
            $insertData = [];
            $unionId=Db::name('mini_program_fans')->where('telephone','in',$request['tel'])->column('unionId');
            $openId = Db::name('wx_gzh_fans')->where('unionid','in',$unionId)->column('openid');
            $model = new GzhSendLog();
            foreach ($openId as $value)
            {
                array_push($insertData,[
                    'user_id'=>$this->userInfo['id'],
                    'template_id'=>$request['template_id'],
                    'status'=>0,
                    'openid'=>$value
                ]);
            }
            $res = $model->saveAll($insertData);
            $data = [];
            exec('php ../think gzhsend',$data);
            print_r($data);
            exit;
        }
        if($res){
            return $this->success($res,'发送成功');
        }else{
            return $this->failed(100,"发送失败");
        }
    }
    public function sends()
    {
        $request = request()->param();
        $where = [];
        $whereOr = [];
        if(!empty($request['telephone']))
        {
            array_push($where,['a.telephone','=',$request['telephone']]);
        }
        if(!empty($request['age']))
        {
            array_push($where,['a.age','=',$request['age']]);
        }
        if(!empty($request['sex']))
        {
            array_push($where,['a.sex','=',$request['sex']]);
        }
        if(!empty($request['scar_id']))
        {
            array_push($where,['b.customer_setting_id_type','=',$request['scar_id']]);
        }
        if(!empty($request['shop_id']))
        {
            array_push($where,['a.shop_id','=',$request['shop_id']]);
        }
        if(!empty($request['shop_type']))
        {
            array_push($where,['c.type','=',$request['shop_type']]);
        }
        if(!empty($request['is_new']))
        {
            if($request['is_new']==1)
            {
                array_push($where,['a.cj_time','=',0]);
            }else{
                array_push($where,['a.cj_time','<>',0]);
            }
        }
        if(!empty($request['effective_entry']))
        {
            if($request['effective_entry']==1)
            {
                array_push($where,['a.first_time','=',0]);
            }else{
                array_push($where,['a.first_time','<>',0]);
            }
        }
        if(!empty($request['member_classification']))
        {
            array_push($where,['a.member_classification','=',$request['member_classification']]);
        }
        if(!empty($request['membership_leve']))
        {
            array_push($where,['a.membership_leve','=',$request['membership_leve']]);
        }
        if(!empty($request['point_min']))
        {
            array_push($where,['d.total','>=',$request['point_min']]);
        }
        if(!empty($request['point_max']))
        {
            array_push($where,['d.total','<=',$request['point_max']]);
        }
        if(!empty($request['consumption_min']))
        {
            array_push($where,['a.consumption','>=',$request['consumption_min']]);
        }
        if(!empty($request['consumption_max']))
        {
            array_push($where,['a.consumption','<=',$request['consumption_max']]);
        }
        if(!empty($request['customer_type']))
        {
            $time = strtotime('-3 month');
            if($request['customer_type']==1)
            {
                array_push($whereOr,['a.final_consumption','>',$time]);
                array_push($whereOr,['a.final_service','>',$time]);
            }else{
                array_push($where,['a.final_consumption','<=',$time]);
                array_push($where,['a.final_service','<=',$time]);
            }
        }
        $result = Db::name('customer')->alias('a')
            ->join('customer_scar b','b.customer_id = a.id','left')
            ->join('shop c','c.shop_id = a.shop_id','left')
            ->join('customer_point d','d.customer_id = a.id','left')
            ->distinct(true)
            ->where($where)
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })->column('a.telephone');
        if(empty($result))
        {
            return $this->failed(100,"无满足条件的用户");
        }
        if($request['type']=="shortMessage")
        {
            $model = new ShortMessageTplModel();
            $res = $model->shortMessageMass($result,$request['tpl_id'],$this->userInfo['id']);
        }else{
            $insertData = [];
            $unionId=Db::name('mini_program_fans')->where('telephone','in',$request['tel'])->column('unionId');
            $openId = Db::name('wx_gzh_fans')->where('unionid','in',$unionId)->column('openid');
            $model = new GzhSendLog();
            foreach ($openId as $value)
            {
                array_push($insertData,[
                    'user_id'=>$this->userInfo['id'],
                    'template_id'=>$request['template_id'],
                    'status'=>0,
                    'openid'=>$value
                ]);
            }
            $res = $model->saveAll($insertData);
            $data = [];
            exec('php ../think gzhsend',$data);
        }
        if($res){
            return $this->success($res,'发送成功');
        }else{
            return $this->failed(100,"发送失败");
        }
    }
    public function weChatGzhTpl()
    {
        $fomateToken = file_get_contents('./token_file/accessTokenWX.json');

        $token_info = json_decode($fomateToken,true);

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            $ACCESS_TOKEN = $token_info['access_token'];

        }else{

            // $getAccessTokenModel = new GetAccessToken();

            // $ACCESS_TOKEN = $getAccessTokenModel->get_access_token_wx();

            $model = new SendUrlModel();

            $url = "https://api.weixin.qq.com/cgi-bin/token";

            $jsonData = [

                'grant_type' => 'client_credential',

                'appid'      => 'wx7cde54d2bb9607e6',

                'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

            ];

            $data = $model->send_url($url,$jsonData);

            $fomateToken = json_decode($data,true);

            $fomateToken['expireTime'] = time() + $fomateToken['expires_in'] - 10;

            // echo "<pre>";
            // print_r($fomateToken);
            // echo "</pre>";

            $newData = json_encode($fomateToken);

            file_put_contents('./token_file/accessTokenWX.json', $newData);

            $ACCESS_TOKEN = $fomateToken['access_token'];

        }
        $posturl = 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token='.$ACCESS_TOKEN;


        // exit;
        $resder = $this->http_curl($posturl,'post','json',[]);
        return $this->success($resder);
    }



    /**
     * 发送请求
     */
    public function http_curl($url,$type,$res,$arr)
    {
        /**
         * $url 请求的url
         * $type 请求类型
         * $res 返回数据类型
         * $arr post请求参数
         */
        $ch=curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,0);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }

    }
}
